package com.huluobo.a2209mdmdemo.myviews

import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.content.Context
import android.view.animation.AccelerateInterpolator
import android.widget.ImageView
import android.widget.RelativeLayout
import com.huluobo.a2209mdmdemo.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.util.Random
import java.util.Timer
import kotlin.concurrent.timerTask

/**
 *  Created by LC on 2025/3/7.
 */
class RedPackView(context: Context) : RelativeLayout(context) {
    private lateinit var timer: Timer

    fun start() {
        timer = Timer()
        timer.schedule(timerTask {
            CoroutineScope(Job()).launch(Dispatchers.Main) {
                val iv = ImageView(context)
                iv.setImageResource(R.drawable.hb)
                val num = Random().nextInt(980)

                val params = LayoutParams(100, 200)
                params.topMargin = 0
                params.leftMargin = num
                iv.layoutParams = params

                val animator = ObjectAnimator.ofFloat(iv, "translationY", 0f, 1920f)
                animator.duration = 2000
                animator.interpolator = AccelerateInterpolator()
                animator.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        super.onAnimationEnd(animation)
                        removeView(iv)
                    }
                })
                animator.start()
                addView(iv)
            }
        }, 0, 10)
    }

    fun stop() {
        timer.cancel()
    }
}